do "E:/ReplicateBuild/02_code/00_environment/00_set_environment.do"

local ss = "ma"
use "$temp/student_level_ma_w_unshrunken_VA", clear


/*
Segregation between schools and within classrooms. Mean share of disadvantaged students among peers, by own type
Do by race and lagged achievement too
*/
		foreach sss in ma rd {
	gen achHi_`sss'=(l_`sss'>0)
	}
	
		cap drop lea schlcode

		ren schid_`ss' schid
		ren lea_`ss' lea
		ren schlcode_`ss' schlcode
		ren teachid_`ss' teachid
		ren section_`ss' section
		ren sidx_`ss' sidx


		* construct class variable
		egen jtidx = group(teachid year schlcode lea)
		sort jtidx section
		gen newsection = jtidx!=jtidx[_n-1] | section!=section[_n-1]
		gen secnum = 1 if jtidx!=jtidx[_n-1]
		replace secnum = secnum[_n-1]+newsection if secnum==.
		
		
keep if lea=="XXX" /// hide identity

sum secnum sidx DISAD sy white achHi_ma

gen nonwhite = 1-white
gen achL = 1-achHi_ma

egen stidx = group(sidx sy)
egen ctidx = group(stidx secnum)

*anova DISAD stidx ctidx

** adjusted r^2 from adding ctidx

foreach aa in DISAD nonwhite achL {
   areg `aa', ab(stidx)
global r2s_`aa' = e(r2_a)
areg `aa', ab(ctidx)
global r2c_`aa' = e(r2_a)


gen non`aa' = 1-`aa'

bys stidx: egen num_`aa'1_s = sum(`aa')
bys stidx: egen num_`aa'0_s = sum(non`aa')

bys ctidx: egen num_`aa'1_c = sum(`aa')
bys ctidx: egen num_`aa'0_c = sum(non`aa')

gen frac`aa'_s = (num_`aa'1_s-`aa')/(num_`aa'1_s+num_`aa'0_s-1)
gen frac`aa'_c = (num_`aa'1_c-`aa')/(num_`aa'1_c+num_`aa'0_c-1) 

summ frac`aa'_s if `aa'==0
global fs0_`aa' = r(mean)

summ frac`aa'_s if `aa'==1
global fs1_`aa' = r(mean)

summ frac`aa'_c if `aa'==0
global fc0_`aa' = r(mean)

summ frac`aa'_c if `aa'==1
global fc1_`aa' = r(mean)

mat m`aa' = (${r2s_`aa'} , ${r2c_`aa'}, ${fs0_`aa'} , ${fs1_`aa'} , ${fc0_`aa'} , ${fc1_`aa'} )
gen m`aa'var = .	
}

label var mDISADvar "Economic disadvantage"
label var mnonwhitevar "Non-white"
label var machLvar "Low lagged achievement"

mat rownames mDISAD = mDISADvar
mat rownames mnonwhite = mnonwhitevar
mat rownames machL = machLvar



mat m = mDISAD\mnonwhite\machL


frmttable using "$tables/segregation_school_classroom", statmat(m) replace va tex fra ///
	ctitles("","Adj R2, Sch","Adj R2, Cls","Sch Peers | Type 0","Sch Peers | Type 1","Cls Peers | Type 0","Cls Peers | Type 1") ///
	sdec(3,3,2,2,2,2\3,3,2,2,2,2\3,3,2,2,2,2\3,3,2,2,2,2) 

